package com.cyzy.filter;

import com.alibaba.fastjson2.JSON;
import com.cyzy.dto.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;


/**
 * token 过滤器
 * 实现全局过滤器
 */
@Component
public class TokenFilter implements GlobalFilter {

    @Autowired
    private RedisTemplate<String,String > redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        /**
         * 获取url        request
         * 1.白名单
         * 2.token
         * 3.无或者过期：  response  友好提示 qwq
         * 4.有： 是否有权限
         */
        //获取request
        ServerHttpRequest request = exchange.getRequest();
        String url = request.getURI().getPath();
        System.out.println("url: " + url);
        String whiteList[] = {"/login", "/reg", "/getCode", "/"}; // 现在是全部放行 带/的都放行
        for (String s : whiteList) {
            if(url.contains(s)){
                return  chain.filter(exchange);
            }
        }

        //白名单


        //redis 是否存在
        ServerHttpResponse response =  exchange.getResponse();
        List<String> list = request.getHeaders().get("Authorization");
        if(list == null || list.isEmpty()  ){
            Result result = Result.error().code(401).message("token不能为空");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
            return response.writeWith(Mono.just(dataBuffer));

        }
        String token = list.get(0);
        boolean re = redisTemplate.hasKey(token.replace("Bearer ", ""));
        if(!re){
            Result result = Result.error().code(401).message("token已过期");
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            response.getHeaders().add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
            DataBuffer dataBuffer = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());
            return response.writeWith(Mono.just(dataBuffer));

        }
        // 获取携带的token

        return chain.filter(exchange);
    }
}
